// DatabaseUtil.java 数据库工具类
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class DatabaseUtil {
	private static final String URL = "jdbc:mysql://localhost:3306/education?useSSL=false&serverTimezone=UTC";
	private static final String USER = "root";
	private static final String PASSWORD = "123456";

	static {
		try {
			Class.forName("com.mysql.cj.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	public static Connection getConnection() throws SQLException {
		return DriverManager.getConnection(URL, USER, PASSWORD);
	}

	public static void saveFeedback(Feedback feedback) throws SQLException {
		String sql = "INSERT INTO feedback (name, email, type, message, create_time) VALUES (?, ?, ?, ?, NOW())";

		try (Connection conn = getConnection();
		     PreparedStatement stmt = conn.prepareStatement(sql)) {

			stmt.setString(1, feedback.getName());
			stmt.setString(2, feedback.getEmail());
			stmt.setString(3, feedback.getFeedbackType());
			stmt.setString(4, feedback.getMessage());
			stmt.executeUpdate();
		}
	}

	public static List<Feedback> getRecentFeedbacks() throws SQLException {
		List<Feedback> list = new ArrayList<>();
		String sql = "SELECT name, email, type, message, create_time FROM feedback ORDER BY create_time DESC LIMIT 5";

		try (Connection conn = getConnection();
		     Statement stmt = conn.createStatement();
		     ResultSet rs = stmt.executeQuery(sql)) {

			while (rs.next()) {
				Feedback fb = new Feedback();
				fb.setName(rs.getString("name"));
				fb.setEmail(rs.getString("email"));
				fb.setFeedbackType(rs.getString("type"));
				fb.setMessage(rs.getString("message"));
				fb.setCreateTime(rs.getTimestamp("create_time"));
				list.add(fb);
			}
		}
		return list;
	}
}